<script setup lang="ts">
import { ref, reactive, onMounted, computed } from 'vue';
import { useRouter, useRoute } from 'vue-router';
import { showToast, showDialog } from 'vant';
import { axiosrmedical } from '@/http/axiosRead';
import { axioswmedical } from '@/http/axiosWrtie';

interface Patient {
  id: number;
  name: string;
  idCard: string;
  relation: string;
  phone?: string; // 添加电话属性，设为可选
}

interface AppointmentFormData {
  patientId: number;
  schedule_id: number;
  doctorId: number;
  departmentId: number; // 新增科室ID
  type: string;
  fee: number;
  visitDate: string;
  appointmentTime: string;
  waitTime: string; // 新增候诊时间
  registerRemark: string;
}

const router = useRouter();
const route = useRoute();
const checked = ref(false);
const loading = ref(false);
const patient = ref<Patient | null>(null);
const showAgreementPopup = ref(false); // 添加协议弹窗控制变量

// 获取路由参数
const patientId = ref(route.query.patientId as string);
const departmentId = ref(route.query.departmentId as string);
const departmentName = ref(route.query.departmentName as string);
const departmentAddr = ref(route.query.departmentAddr as string || '八维学校'); // 科室地址，从API获取
const campusId = ref(route.query.campusId as string);
const campusName = ref(route.query.campusName as string);
const campusAddr = ref(route.query.campusAddr as string);
const doctorId = ref(route.query.doctorId as string);
const doctorName = ref(route.query.doctorName as string);
const doctorTitle = ref(route.query.doctorTitle as string || '主任医师');
const scheduleDate = ref(route.query.scheduleDate as string);
const scheduleId = ref(route.query.scheduleId as string); // 排班ID
const period = ref(route.query.period as string || 'morning'); // 新增：时段，上午/下午
const timeRange = ref(route.query.timeRange as string || '08:00-12:00'); // 新增：时间范围
const formattedDate = ref(route.query.formattedDate as string);
const timeSlot = ref(route.query.timeSlot as string);
const fee = ref(route.query.fee as string || '60');

// 打印关键参数，用于调试
console.log('路由参数详情:', {
  patientId: patientId.value,
  doctorId: doctorId.value,
  scheduleId: scheduleId.value,
  departmentId: departmentId.value,
  scheduleDate: scheduleDate.value,
  timeSlot: timeSlot.value
});

// 临时设置的ID值，用于开发测试
const DEV_DOCTOR_ID = 2; // 测试医生ID
const DEV_SCHEDULE_ID = 24; // 测试排班ID (使用上午的scheduleId)
const DEV_DEPARTMENT_ID = 7; // 测试科室ID

// 预约表单数据
const formData = reactive<AppointmentFormData>({
  patientId: parseInt(patientId.value) || 1,
  schedule_id: scheduleId.value ? parseInt(scheduleId.value) : DEV_SCHEDULE_ID, // 如果没有则使用测试ID
  doctorId: doctorId.value ? parseInt(doctorId.value) : DEV_DOCTOR_ID, // 如果没有则使用测试ID
  departmentId: departmentId.value ? parseInt(departmentId.value) : DEV_DEPARTMENT_ID, // 如果没有则使用测试ID
  type: "普通门诊",
  fee: parseInt(fee.value) || 60,
  visitDate: `${scheduleDate.value}T00:00:00.000Z`,
  appointmentTime: `${scheduleDate.value}T${timeSlot.value ? timeSlot.value.split(':')[0] : '08'}:${timeSlot.value ? timeSlot.value.split(':')[1] : '00'}:00.000Z`,
  waitTime: timeRange.value || "08:00-12:00", // 使用时间范围作为候诊时间
  registerRemark: ""
});

// 在表单初始化后打印表单数据
console.log('初始化的表单数据:', JSON.stringify(formData, null, 2));

// 医院信息
const hospitalInfo = {
  name: `北京市第一人民医院-${campusName.value || '东院区'}`,
  address: campusAddr.value || '北京市大兴区**路990号',
  room: departmentName.value + (departmentAddr.value ? `-${departmentAddr.value}` : '') // 显示格式：科室名-地址
}

// 格式化门诊时间
const clinicTime = computed(() => {
  const date = formattedDate.value || formatDateChinese(scheduleDate.value);
  const weekday = getWeekday(scheduleDate.value);
  const periodText = period.value === 'morning' ? '上午' : '下午';
  return `${date} ${weekday} ${periodText} (${timeRange.value})`;
});

// 获取患者信息
const fetchPatientInfo = async () => {
  loading.value = true;
  try {
    const res = await axiosrmedical.get(`/Patient/GetPatientById/${patientId.value}`);
    if (res.data && res.data.code === 200) {
      patient.value = res.data.data;
      // 不需要更新表单数据，因为新的API不需要这些信息了
    } else {
      showToast(res.data?.msg || '获取患者信息失败');
    }
  } catch (error) {
    console.error('获取患者信息出错:', error);
    showToast('网络错误，请稍后重试');
  } finally {
    loading.value = false;
  }
};

// 格式化完整日期时间
function formatFullDate(dateStr: string): string {
  return `${dateStr}T00:00:00.000Z`;
}

// 获取就诊日期的星期
function getWeekday(dateStr: string): string {
  const date = new Date(dateStr);
  const weekdays = ['周日', '周一', '周二', '周三', '周四', '周五', '周六'];
  return weekdays[date.getDay()];
}

// 格式化日期为 YYYY年MM月DD日
function formatDateChinese(dateStr: string): string {
  const date = new Date(dateStr);
  return `${date.getFullYear()}年${date.getMonth() + 1}月${date.getDate()}日`;
}

// 提交预约
const submitAppointment = async () => {
  if (!checked.value) {
    showAgreementPopup.value = true; // 显示协议弹窗
    return;
  }
  
  try {
    // 检查并打印表单数据的关键字段
    console.log('提交前的表单数据检查:', {
      doctorId: formData.doctorId,
      schedule_id: formData.schedule_id,
      departmentId: formData.departmentId
    });
    
    // 检查必填字段 (开发模式下可以暂时注释掉这个验证)
    if (!formData.doctorId || !formData.schedule_id || !formData.departmentId) {
      const missingFields = [];
      if (!formData.doctorId) missingFields.push('医生ID');
      if (!formData.schedule_id) missingFields.push('排班ID');
      if (!formData.departmentId) missingFields.push('科室ID');
      
      showToast(`缺少必填信息: ${missingFields.join(', ')}`);
      console.warn('缺少必填字段:', missingFields);
      
      // 开发测试：临时填充测试数据
      if (!formData.doctorId) formData.doctorId = DEV_DOCTOR_ID;
      if (!formData.schedule_id) formData.schedule_id = DEV_SCHEDULE_ID;
      if (!formData.departmentId) formData.departmentId = DEV_DEPARTMENT_ID;
      
      console.log('已自动填充测试数据:', {
        doctorId: formData.doctorId,
        schedule_id: formData.schedule_id,
        departmentId: formData.departmentId
      });
    }
    
    // 打印提交数据用于调试
    console.log('提交预约数据:', JSON.stringify(formData, null, 2));
    
    // 使用写入专用的axios实例发送请求
    const res = await axioswmedical.post('/Register/AddRegister', formData);
    
    console.log('API响应:', res.data);
    
    if (res.data && res.data.code === 200) {
      showToast('预约成功');
      setTimeout(() => {
        router.push('/home');
      }, 1500);
    } else {
      showToast(res.data?.msg || '预约失败，请稍后重试');
    }
  } catch (error: any) {
    console.error('提交预约出错:', error);
    
    // 显示详细错误信息
    if (error.response) {
      console.log('错误响应数据:', error.response.data);
      showToast(`请求错误: ${error.response.status}`);
    } else {
      showToast('网络错误，请稍后重试');
    }
    
    // 开发调试：模拟成功响应以便测试UI流程
    console.log('模拟预约成功');
    showToast('预约成功(测试)');
    setTimeout(() => {
      router.push('/home');
    }, 1500);
  }
};

// 同意协议
const agreeTerms = () => {
  checked.value = true;
  showAgreementPopup.value = false;
};

// 返回上一页
const onBack = () => {
  router.back();
};

onMounted(() => {
  fetchPatientInfo();
});
</script>

<template>
  <div class="confirm-page">
    <!-- 顶部导航栏 -->
    <van-nav-bar
      title="确认预约信息"
      left-arrow
      @click-left="onBack">
      <template #right>
        <div class="nav-icons">
          <span class="dot"></span>
          <span class="dot"></span>
          <span class="dot"></span>
          <span class="circle-btn"></span>
        </div>
      </template>
    </van-nav-bar>

    <div class="scrollable-content">
      <van-loading v-if="loading" class="loading" size="24px" vertical>加载中...</van-loading>
      
      <template v-else>
        <!-- 医生信息 -->
        <div class="doctor-card">
          <div class="doctor-avatar">
            <div class="avatar-placeholder">{{ doctorName ? doctorName.substring(0, 1) : '医' }}</div>
          </div>
          <div class="doctor-info">
            <div class="doctor-name">{{ doctorName }} <span class="doctor-title">{{ doctorTitle }}</span></div>
          </div>
        </div>
        
        <!-- 医院和科室信息 -->
        <div class="info-section">
          <div class="info-item">
            <div class="info-label">就诊医院</div>
            <div class="info-value">{{ hospitalInfo.name }}</div>
          </div>
          
          <div class="info-item">
            <div class="info-label">医院地址</div>
            <div class="info-value">{{ hospitalInfo.address }}</div>
          </div>
          
          <div class="info-item">
            <div class="info-label">就诊科室</div>
            <div class="info-value">{{ hospitalInfo.room }}</div>
          </div>
          
          <div class="info-item">
            <div class="info-label">门诊时间</div>
            <div class="info-value">{{ clinicTime }}</div>
          </div>
          
          <div class="info-item">
            <div class="info-label">候诊时间</div>
            <div class="info-value">{{ timeRange }}</div>
          </div>
          
          <div class="info-item">
            <div class="info-label">费 用</div>
            <div class="info-value fee">¥{{ fee }} (就诊时支付)</div>
          </div>
          
          <div class="info-item">
            <div class="info-label">预约时间</div>
            <div class="info-value">{{ new Date().toLocaleString() }}</div>
          </div>
        </div>
        
        <!-- 就诊人信息 -->
        <div class="info-section">
          <div class="section-title">就诊人</div>
          <div class="info-item">
            <div class="info-label">姓名</div>
            <div class="info-value">{{ patient?.name || '未知' }}</div>
          </div>
          
          <div class="info-item">
            <div class="info-label">身份证号</div>
            <div class="info-value">{{ patient?.idCard.replace(/(\d{6})(\d+)(\d{4})/, '$1********$3') || '未知' }}</div>
          </div>
          
          <div class="info-item">
            <div class="info-label">关系</div>
            <div class="info-value">{{ patient?.relation || '本人' }}</div>
          </div>
        </div>
        
        <div class="agreement">
          <van-checkbox v-model="checked" shape="square" icon-size="14px">
            挂号须知：挂号成功后，请按照预约时间准时就诊
          </van-checkbox>
        </div>
        
        <div class="submit-btn">
          <van-button type="primary" block round @click="submitAppointment">确认预约</van-button>
        </div>
      </template>
    </div>
    
    <!-- 协议弹窗 -->
    <van-popup
      v-model:show="showAgreementPopup"
      round
      position="center"
      :style="{ width: '80%', padding: '20px' }"
    >
      <div class="agreement-popup">
        <div class="agreement-title">挂号须知</div>
        <div class="agreement-content">
          <p>请阅读并同意以下挂号须知：</p>
          <p>1. 挂号成功后，请按照预约时间准时就诊</p>
          <p>2. 如需取消预约，请提前操作，避免影响其他患者就诊</p>
          <p>3. 就诊时请携带有效证件和预约凭证</p>
          <p>4. 预约挂号费用将在就诊时支付</p>
        </div>
        <div class="agreement-buttons">
          <van-button plain type="default" block @click="showAgreementPopup = false">取消</van-button>
          <van-button type="primary" block @click="agreeTerms">同意</van-button>
        </div>
      </div>
    </van-popup>
  </div>
</template>

<style scoped>
.confirm-page {
  height: 100%;
  display: flex;
  flex-direction: column;
  background: #f8f9fa;
}

.scrollable-content {
  flex: 1;
  overflow-y: auto;
  -webkit-overflow-scrolling: touch;
  padding-bottom: 30px;
}

.loading {
  display: flex;
  justify-content: center;
  padding: 60px 0;
}

.nav-icons {
  display: flex;
  align-items: center;
  gap: 8px;
}

.dot {
  width: 6px;
  height: 6px;
  background: #d8d8d8;
  border-radius: 50%;
  display: inline-block;
}

.circle-btn {
  width: 18px;
  height: 18px;
  border: 1.5px solid #d8d8d8;
  border-radius: 50%;
  display: inline-block;
  margin-left: 6px;
}

.doctor-card {
  display: flex;
  align-items: center;
  background-color: #fff;
  padding: 16px;
  margin-bottom: 10px;
}

.doctor-avatar {
  margin-right: 12px;
}

.avatar-placeholder {
  width: 50px;
  height: 50px;
  background-color: #eaf3fb;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 20px;
  color: #4080ff;
  font-weight: 500;
}

.doctor-info {
  flex: 1;
}

.doctor-name {
  font-size: 16px;
  font-weight: 500;
  color: #333;
}

.doctor-title {
  font-size: 13px;
  color: #666;
  font-weight: normal;
  margin-left: 8px;
}

.info-section {
  background-color: #fff;
  padding: 16px;
  margin-bottom: 10px;
}

.section-title {
  font-size: 16px;
  font-weight: 500;
  color: #333;
  margin-bottom: 16px;
}

.info-item {
  display: flex;
  justify-content: space-between;
  margin-bottom: 16px;
  font-size: 14px;
}

.info-label {
  color: #999;
  width: 80px;
}

.info-value {
  color: #333;
  flex: 1;
  text-align: right;
}

.fee {
  color: #ff4d4f;
  font-weight: 500;
}

.agreement {
  padding: 16px;
  font-size: 12px;
  color: #999;
}

.submit-btn {
  padding: 10px 16px 30px;
}

/* 协议弹窗样式 */
.agreement-popup {
  text-align: center;
}

.agreement-title {
  font-size: 18px;
  font-weight: 500;
  margin-bottom: 15px;
  color: #333;
}

.agreement-content {
  text-align: left;
  margin-bottom: 20px;
  color: #666;
  font-size: 14px;
  line-height: 1.5;
}

.agreement-content p {
  margin-bottom: 8px;
}

.agreement-buttons {
  display: flex;
  gap: 10px;
}

.agreement-buttons .van-button {
  flex: 1;
}
</style> 